package com.weetop.cfw

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.*
import com.king.app.dialog.AppDialog
import com.king.app.dialog.AppDialogConfig
import com.king.app.updater.AppUpdater
import com.king.app.updater.http.OkHttpManager
import com.weetop.cfw.base.presenter.imp.MainPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.ui.fragment.CommonBaseFragment
import com.weetop.cfw.base.view.MainView
import com.weetop.cfw.bean.AppVersionBean
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.event.KindTabSelectedEvent
import com.weetop.cfw.event.ShowKindFragmentEvent
import com.weetop.cfw.home_page.activity.PlantSalePublishActivity
import com.weetop.cfw.home_page.activity.PublishActivity
import com.weetop.cfw.home_page.fragment.HomePageFragment
import com.weetop.cfw.kind.fragment.KindFragment
import com.weetop.cfw.message.fragment.MessageFragment
import com.weetop.cfw.mine.fragment.MineFragment
import com.weetop.cfw.utils.EventBusUtils
import com.weetop.cfw.utils.LogInUtils
import com.weetop.cfw.utils.MMKVUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.system.exitProcess


class MainActivity : CommonBaseActivity(), View.OnClickListener, MainView {

    private lateinit var mainPresenterImp: MainPresenterImp

    private val homePageFragment: HomePageFragment = HomePageFragment()
    private val kindFragment: KindFragment = KindFragment()
    private val messageFragment: MessageFragment = MessageFragment()
    private val mineFragment: MineFragment = MineFragment()

    private lateinit var publishPopupWindow: PopupWindow

    private lateinit var publishView: View

    private lateinit var imageClosePublishPopupWindow: ImageView

    private lateinit var linearWorkshopRentOut: LinearLayout
    private lateinit var linearPlantSale: LinearLayout
    private lateinit var linearWarehouseRental: LinearLayout
    private lateinit var linearWarehouseSale: LinearLayout

    //用户上一次点击回退键的时间
    private var exitTime = 0L

    private val commonBaseFragmentList =
        listOf(homePageFragment, kindFragment, messageFragment, mineFragment)

    override fun getLayoutId() = R.layout.activity_main

    override fun initView(savedInstanceState: Bundle?) {
        mainPresenterImp = MainPresenterImp()
        mainPresenterImp.attachView(this)

        initPublishPopupWindow()

        mainViewPager.setCurrentItem(0, true)
        mainViewPager.setNoScroll(true)
        initBottomNavigationTextAndIcon(0)

        mainViewPager.offscreenPageLimit = 4

        setViewsOnClickListener(
            this,
            linearMine,
            linearMessage,
            linearPublish,
            linearKind,
            linearHomePage
        )

        mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                initBottomNavigationTextAndIcon(position)
            }

        })
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtils.showShort("再次点击退出APP")
                exitTime = System.currentTimeMillis()
            } else {
                ActivityUtils.finishActivity(this)
                exitProcess(0)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun initBottomNavigationTextAndIcon(position: Int) {
        when (position) {
            0 -> {
                EventBusUtils.post(ShowKindFragmentEvent(false))
                textHomePage.setTextColor(ColorUtils.getColor(R.color.c_1381CC))
                textKind.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textMessage.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textMine.setTextColor(ColorUtils.getColor(R.color.colorAccent))

                imageHomePage.setImageResource(R.mipmap.home_page_selected_logo)
                imageKind.setImageResource(R.mipmap.kind_unselected_logo)
                imageMessage.setImageResource(R.mipmap.message_unselected_logo)
                imageMine.setImageResource(R.mipmap.mine_unselected_logo)
            }
            1 -> {
                EventBusUtils.post(ShowKindFragmentEvent(true))
                textHomePage.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textKind.setTextColor(ColorUtils.getColor(R.color.c_1381CC))
                textMessage.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textMine.setTextColor(ColorUtils.getColor(R.color.colorAccent))

                imageHomePage.setImageResource(R.mipmap.home_page_unselected_logo)
                imageKind.setImageResource(R.mipmap.kind_selected_logo)
                imageMessage.setImageResource(R.mipmap.message_unselected_logo)
                imageMine.setImageResource(R.mipmap.mine_unselected_logo)
            }
            2 -> {
                EventBusUtils.post(ShowKindFragmentEvent(false))
                textHomePage.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textKind.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textMessage.setTextColor(ColorUtils.getColor(R.color.c_1381CC))
                textMine.setTextColor(ColorUtils.getColor(R.color.colorAccent))

                imageHomePage.setImageResource(R.mipmap.home_page_unselected_logo)
                imageKind.setImageResource(R.mipmap.kind_unselected_logo)
                imageMessage.setImageResource(R.mipmap.message_selected_logo)
                imageMine.setImageResource(R.mipmap.mine_unselected_logo)
            }
            else -> {
                EventBusUtils.post(ShowKindFragmentEvent(false))
                textHomePage.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textKind.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textMessage.setTextColor(ColorUtils.getColor(R.color.colorAccent))
                textMine.setTextColor(ColorUtils.getColor(R.color.c_1381CC))

                imageHomePage.setImageResource(R.mipmap.home_page_unselected_logo)
                imageKind.setImageResource(R.mipmap.kind_unselected_logo)
                imageMessage.setImageResource(R.mipmap.message_unselected_logo)
                imageMine.setImageResource(R.mipmap.mine_selected_logo)
            }
        }
    }


    /**
     * 初始化发布界面的PopupWindow
     */
    private fun initPublishPopupWindow() {
        publishView = View.inflate(this, R.layout.popupwindow_publich, null)
        linearWorkshopRentOut = publishView.findViewById(R.id.linearWorkshopRentOut)
        linearPlantSale = publishView.findViewById(R.id.linearPlantSale)
        linearWarehouseRental = publishView.findViewById(R.id.linearWarehouseRental)
        imageClosePublishPopupWindow = publishView.findViewById(R.id.imageClosePublishPopupWindow)
        linearWarehouseSale = publishView.findViewById(R.id.linearWarehouseSale)

        imageClosePublishPopupWindow.setOnClickListener {
            publishPopupWindow.dismiss()
        }
        linearWorkshopRentOut.setOnClickListener {
            publishPopupWindow.dismiss()
            if (LogInUtils.userIsLogIn()) {
                PublishActivity.startPublishActivity(
                    this@MainActivity,
                    isEditPublishInfo = false,
                    isWorkshopOrWareHouse = true
                )
            }
        }

        linearPlantSale.setOnClickListener {
            publishPopupWindow.dismiss()
            if (LogInUtils.userIsLogIn()) {
                PlantSalePublishActivity.startPlantSalePublishActivity(
                    this@MainActivity,
                    editPublish = false,
                    isWorkShopOrWarehouse = true
                )
            }
        }

        linearWarehouseRental.setOnClickListener {
            publishPopupWindow.dismiss()
            if (LogInUtils.userIsLogIn()) {
                PublishActivity.startPublishActivity(
                    this@MainActivity,
                    isEditPublishInfo = false,
                    isWorkshopOrWareHouse = false
                )
            }
        }

        linearWarehouseSale.setOnClickListener {
            publishPopupWindow.dismiss()
            if (LogInUtils.userIsLogIn()) {
                PlantSalePublishActivity.startPlantSalePublishActivity(
                    this@MainActivity,
                    editPublish = false,
                    isWorkShopOrWarehouse = false
                )
            }
        }

        publishPopupWindow = PopupWindow(this)
        publishPopupWindow.contentView = publishView
        publishPopupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
        publishPopupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        publishPopupWindow.isFocusable = true
        publishPopupWindow.isOutsideTouchable = true
        publishPopupWindow.setBackgroundDrawable(
            ContextCompat.getDrawable(
                this,
                R.drawable.solid_white_shape
            )
        )


        publishPopupWindow.setOnDismissListener {
            windowStartLight()
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.linearHomePage -> {
                if (mainViewPager.currentItem != 0) {
                    mainViewPager.setCurrentItem(0, true)
                }
            }
            R.id.linearKind -> {
                if (mainViewPager.currentItem != 1) {
                    mainViewPager.setCurrentItem(1, true)
                    EventBusUtils.postSticky(KindTabSelectedEvent())
                }
            }
            R.id.linearPublish -> {
                EventBusUtils.post(ShowKindFragmentEvent(false))
                publishPopupWindow.showAtLocation(linearMain, Gravity.BOTTOM, 0, 0)
                windowStartDark()
            }
            R.id.linearMessage -> {
                if (LogInUtils.userIsLogIn()) {//表示用户已经登录
                    if (mainViewPager.currentItem != 2) {
                        mainViewPager.setCurrentItem(2, true)
                    }
                }
            }
            R.id.linearMine -> {
                if (LogInUtils.userIsLogIn()) {//表示用户已经登录
                    if (mainViewPager.currentItem != 3) {
                        mainViewPager.setCurrentItem(3, true)
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mainPresenterImp.detachView()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val currentItem = intent?.getIntExtra(CURRENT_ITEM, 0)
        mainViewPager.currentItem = currentItem!!
        setIntent(intent)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mainViewPager.adapter = MainViewPagerAdapter(supportFragmentManager, commonBaseFragmentList)

        val currentItem = intent.getIntExtra(CURRENT_ITEM, 0)
        mainViewPager.currentItem = currentItem

        mainPresenterImp.checkAppVersionInfo(this)

        //LogUtils.e("token", MMKVUtils.getToken())
    }

    companion object {

        private const val CURRENT_ITEM = "CURRENT_ITEM"

        fun startMainActivity(context: Context, currentItem: Int) {
            val intent = Intent(context, MainActivity::class.java)
            intent.putExtra(CURRENT_ITEM, currentItem)
            ActivityUtils.startActivity(intent)
        }
    }

    private class MainViewPagerAdapter(
        fragmentManager: FragmentManager,
        private var commonBaseFragmentList: List<CommonBaseFragment>
    ) : FragmentStatePagerAdapter(fragmentManager) {

        override fun getItem(position: Int) = commonBaseFragmentList[position]

        override fun getCount() = commonBaseFragmentList.size

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//            super.destroyItem(container, position, `object`)
        }

    }

    /**
     * App版本信息获取成功
     */
    override fun appVersionInfoGetSuccess(appVersionBean: AppVersionBean?) {
        if (appVersionBean != null) {
            if (appVersionBean.hasnew == 1 && appVersionBean.verno.toInt() > AppUtils.getAppVersionCode()) {//有最新版本
                val config = AppDialogConfig()
                config.apply {
                    title = "APP更新"
                    ok = "立即更新"
                    cancel = "暂不更新"
                    content = appVersionBean.upcon
                    onClickOk = View.OnClickListener {
                        AppUpdater.Builder()
                            .serUrl("${UrlConstants.baseUrl}${appVersionBean.verfile}")
                            .setFilename("mhcf.apk")
                            .build(this@MainActivity)
                            .setHttpManager(OkHttpManager.getInstance())//使用OkHttpClient实现下载，需依赖okhttp库
                            .start()
                        AppDialog.INSTANCE.dismissDialogFragment(supportFragmentManager)
                    }
                    onClickCancel = View.OnClickListener {
                        AppDialog.INSTANCE.dismissDialogFragment(supportFragmentManager)
                    }
                }
                AppDialog.INSTANCE.showDialogFragment(supportFragmentManager, config);
            }
        }
    }
}
